package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.ListNode;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 排序链表
 * https://leetcode.cn/problems/sort-list/
 *
 * @time 2024/1/19
 */
public class SortList {

//    public static void main(String[] args) {
//        SortList sl = new SortList();
//        ListNode l_1 = new ListNode(-1);
//        ListNode l0 = new ListNode(0);
//        ListNode l1 = new ListNode(1);
//        ListNode l2 = new ListNode(2);
//        ListNode l3 = new ListNode(3);
//        ListNode l4 = new ListNode(4);
//        ListNode l5 = new ListNode(5);
//
////        l_1.next = l5;
////        l5.next = l3;
////        l3.next = l4;
////        l4.next = l0;
//
//        l4.next = l2;
//        l2.next = l1;
//        l1.next = l3;
//        sl.sortList(l4);
//    }

    public ListNode sortList(ListNode head) {
        List<Integer> list = toList(head);
        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        });
        ListNode tmp = head;
        for (Integer num : list) {
            tmp.val = num;
            tmp = tmp.next;
        }
        return head;
    }

    private List<Integer> toList(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        return list;
    }
}
